package com.yidu.qianfeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yidu.qianfeng.common.bean.company.EmpInfo;
import com.yidu.qianfeng.common.util.StrUtil;
import com.yidu.qianfeng.mapper.EmpInfoMapper;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: 匡兆杰
 * @Description: UserDetails登录认证业务实现
 * @Date Created in 14:31 2021/3/3
 */

@Service("userDetailsService")
public class QfUserDetailsService implements UserDetailsService {

    //注入员工信息实体数据映射
    @Resource(name = "empInfoMapper")
    private EmpInfoMapper empInfoMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户是否存在，根据员工账号
        QueryWrapper<EmpInfo> queryWrapper = new QueryWrapper<>();
        //username匹配eq条件员工账号emp_account
        queryWrapper.eq("emp_account", username);
        //查询单个员工信息
        EmpInfo empInfo = empInfoMapper.selectOne(queryWrapper);


        //查询员工模块权限List
        List<String> modelAuthList = empInfoMapper.selectEmpModelAuth(empInfo.getUsername());
        //查询员工页面权限List排除模块权限，需要两个参数：empInfo,modelAuthList
        List<String> pageAuthExcludeModel = empInfoMapper.selectEmpPageAuthExcludeModel(empInfo.getEmpAccount(), modelAuthList);

        //模块权限字符串
        String modelAuthListStr = "";
        //页面权限字符串
        String pageAuthExcludeModelStr = "";

        //判断模块权限列表非空
        if (!modelAuthList.isEmpty()){
            //模块权限列表转换成字符串，并调用StrUtil工具类去除首尾的第一个字母
            modelAuthListStr = StrUtil.excludeFirstLastChar(modelAuthList.toString());

        }
        //判断页面权限列表非空
        if (!pageAuthExcludeModel.isEmpty()){
            //页面权限列表转换成字符串，并调用StrUtil工具类去除首尾的第一个字母
            pageAuthExcludeModelStr = StrUtil.excludeFirstLastChar(pageAuthExcludeModel.toString());

        }
        //判断模块权限列表非空||页面权限非空
        if (!modelAuthList.isEmpty() || !pageAuthExcludeModel.isEmpty()){
            //添加到员工信息的权限列表中，调用AuthorityUtils的字符串权限转list方法
            empInfo.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(modelAuthListStr+","+pageAuthExcludeModelStr));

        }

        return empInfo;
    }


}
